<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/22
 * Time: 10:02
 * * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\home\controller;

use app\common\model\AmountLog;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\LevelOrder;
use app\common\model\MessageTemplate;
use app\common\model\RechargeOrder;
use app\common\model\UserCommission;
use app\common\model\UserLevel;
use think\Exception;

class Callback
{

    public function levelGzhOrder()
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'Vipdata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $pay_type = Config::getConfigValue('pay_type');
        if ($pay_type == 1) {
            $apiKey = Config::getConfigValue('gzh_apikey_v3');
        } else {
            $apiKey = Config::getConfigValue('gzh_m_apikey_v3');
        }
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $apiKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $levelOrderModel = new  LevelOrder();
            $levelOrderInfo = $levelOrderModel->where(['order_sn' => $out_trade_no])->find();
            if ($pay_money != $levelOrderInfo['price']) {
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($levelOrderInfo['status'] != 1) {
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }
            $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 3]);
            $userModel = new \app\common\model\User();
            try {
                $userLevelModel = new UserLevel();
                $levelModel = new Level();
                $levelInfo = $levelModel->where(['id' => $levelOrderInfo['level_id']])->find();
                $userLevelInfo = $userLevelModel->where(['level_id' => $levelOrderInfo['level_id'], 'uid' => $levelOrderInfo['uid']])->find();
                if ($userLevelInfo) {
                    $startTime = strtotime($userLevelInfo['start_time']);
                    if ($userLevelInfo['status'] == 1) { // 会员等级有效 延长 vip
                        $endTime = strtotime( $userLevelInfo['end_time']) +86400 * $levelInfo['effective_time'];
                        $userLevelModel->where(['uid' => $levelOrderInfo['uid'], 'level_id' => $levelOrderInfo['level_id']])->update(['end_time' => $endTime]);
                    } else { // 无效修改等级时长
                        $startTime = time();
                        $endTime = $startTime  +86400 * $levelInfo['effective_time'];
                        $userLevelModel
                            ->where(['uid' => $levelOrderInfo['uid'], 'level_id' => $levelOrderInfo['level_id']])
                            ->update(['end_time' => $endTime, 'start_time' => $startTime]);
                        $userModel->where(['id' => $levelOrderInfo['uid']])->update(['level_id' => $levelOrderInfo['id'], 'level_name' => $levelInfo['name']]);
                    }
                } else {
                    $startTime = time();
                    $endTime =  $startTime +86400 * $levelInfo['effective_time'];
                    $data = [
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'uid' => $levelOrderInfo['uid'],
                        'level_id' => $levelInfo['id'],
                        'level' => $levelInfo['level'],
                    ];
                    $userLevelModel->insert($data);
                    $userMode = new \app\common\model\User();
                    $userMode->where(['id' => $levelOrderInfo['uid']])->update(['level_id' => $levelInfo['id'], 'level_name' => $levelInfo['name']]);
                }
                $lowLevel = $userLevelModel->where('level', '<', $levelInfo['level'])->where(['uid' => $levelOrderInfo['uid'], 'status' => 1])->select()->toArray();
                if ($lowLevel) {
                    foreach ($lowLevel as $value) {
                        $effectiveTime = abs($value['time'] - time()) / 86400;
                        $lowLevelTime = $endTime + $effectiveTime;
                        $userLevelModel->where(['id' => $value['id']])->update(['end_time' => $lowLevelTime])->update();
                    }
                }
                $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 2,'pay_time' => time()]);
                $userCommission  = new UserCommission();
                $userCommission->vipCommission($levelOrderInfo['uid'],$levelOrderInfo['id'],$levelInfo['first_commission'],$levelInfo['second_commission']);

                $gzhMessage[0]['data'] = [
                    'amount10' => ['value' => $levelOrderInfo['price'].'元'],
                    'time4' => ['value' =>date('Y-m-d H:i:s',$startTime)],
                    'time5' => ['value' => date('Y-m-d H:i:s',$endTime)],
                ];
                $gzhMessage[0]['uid'] = $levelOrderInfo['uid'];
                $gzhMessage[0]['title'] ='vip';
                $messageModel = new MessageTemplate();
                $messageModel->sendMessage(1,$gzhMessage);
            } catch (Exception $exception) {
                file_put_contents('./' . date('Y-m-d') . 'viplogerror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
    public function levelXcxOrder()
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'Vipdata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $pay_type = Config::getConfigValue('pay_type');
        if ($pay_type == 1) {
            $apiKey = Config::getConfigValue('xcx_apikey_v3');
        } else {
            $apiKey = Config::getConfigValue('xcx_m_apikey_v3');
        }
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $apiKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $levelOrderModel = new  LevelOrder();
            $levelOrderInfo = $levelOrderModel->where(['order_sn' => $out_trade_no])->find();
            if ($pay_money != $levelOrderInfo['price']) {
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($levelOrderInfo['status'] != 1) {
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }
            $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 3]);
            $userModel = new \app\common\model\User();
            try {
                $userLevelModel = new UserLevel();
                $levelModel = new Level();
                $levelInfo = $levelModel->where(['id' => $levelOrderInfo['level_id']])->find();
                $userLevelInfo = $userLevelModel->where(['level_id' => $levelOrderInfo['level_id'], 'uid' => $levelOrderInfo['uid']])->find();
                if ($userLevelInfo) {
                    $startTime = strtotime($userLevelInfo['start_time']);
                    if ($userLevelInfo['status'] == 1) { // 会员等级有效 延长 vip
                        $endTime = strtotime( $userLevelInfo['end_time']) +86400 * $levelInfo['effective_time'];
                        $userLevelModel->where(['uid' => $levelOrderInfo['uid'], 'level_id' => $levelOrderInfo['level_id']])->update(['end_time' => $endTime]);
                    } else { // 无效修改等级时长
                        $startTime = time();
                        $endTime = $startTime  +86400 * $levelInfo['effective_time'];
                        $userLevelModel
                            ->where(['uid' => $levelOrderInfo['uid'], 'level_id' => $levelOrderInfo['level_id']])
                            ->update(['end_time' => $endTime, 'start_time' => $startTime]);
                        $userModel->where(['id' => $levelOrderInfo['uid']])->update(['level_id' => $levelOrderInfo['id'], 'level_name' => $levelInfo['name']]);
                    }
                } else {
                    $startTime = time();
                    $endTime =  $startTime +86400 * $levelInfo['effective_time'];
                    $data = [
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'uid' => $levelOrderInfo['uid'],
                        'level_id' => $levelInfo['id'],
                        'level' => $levelInfo['level'],
                    ];
                    $userLevelModel->insert($data);
                    $userMode = new \app\common\model\User();
                    $userMode->where(['id' => $levelOrderInfo['uid']])->update(['level_id' => $levelInfo['id'], 'level_name' => $levelInfo['name']]);
                }
                $lowLevel = $userLevelModel->where('level', '<', $levelInfo['level'])->where(['uid' => $levelOrderInfo['uid'], 'status' => 1])->select()->toArray();
                if ($lowLevel) {
                    foreach ($lowLevel as $value) {
                        $effectiveTime = abs($value['time'] - time()) / 86400;
                        $lowLevelTime = $endTime + $effectiveTime;
                        $userLevelModel->where(['id' => $value['id']])->update(['end_time' => $lowLevelTime])->update();
                    }
                }
                $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 2,'pay_time' => time()]);
                $userInfo = $userModel->where(['id' => $levelOrderInfo['uid']])->find();
                $userCommission  = new UserCommission();
                $userCommission->vipCommission($levelOrderInfo['uid'],$levelOrderInfo['id'],$levelInfo['first_commission'],$levelInfo['second_commission']);

                $xcxMessage[0]['data'] = [
                    'amount9' => ['value' => $pay_money],
                    'name4' => ['value' => $userInfo['nickname']],
                    'date1' => ['value' =>date('Y-m-d',$startTime)],
                    'date2' => ['value' => date('Y-m-d',$endTime)],
                ];
                $xcxMessage[0]['uid'] =$levelOrderInfo['uid'];
                $xcxMessage[0]['title'] ='vip';
                $messageModel = new MessageTemplate();
                $messageModel->sendMessage(3,$xcxMessage);
            } catch (Exception $exception) {
                file_put_contents('./' . date('Y-m-d') . 'viperror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $levelOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }

    }

    public function rechargeGzhOrder(){
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'rechargedata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $pay_type = Config::getConfigValue('pay_type');
        if ($pay_type == 1) {
            $apiKey = Config::getConfigValue('gzh_apikey_v3');
        } else {
            $apiKey = Config::getConfigValue('gzh_m_apikey_v3');
        }
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $apiKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);

        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $rechargeOrderModel = new RechargeOrder();
            $rechargeOrderInfo =  $rechargeOrderModel->where(['order_sn' =>$out_trade_no] )->find();
            if(empty($rechargeOrderInfo)){
                return \json([
                    "code" => "FAIL",
                    "message" => "订单不存在"
                ]);
            }
            if ($rechargeOrderInfo['status'] != 1){
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }
            if ($pay_money != $rechargeOrderInfo['price']) {
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 3]);
            $userModel = new \app\common\model\User();
            try {
                $rechargeOrderModel->startTrans();
                $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 2,'pay_time' => time()]);
                $totalNumber = bcadd($rechargeOrderInfo['amount'],$rechargeOrderInfo['give_amount'],2);
                $userModel->where(['id' => $rechargeOrderInfo['uid']])->inc('balance',$totalNumber)->update();
                $amountModel = new AmountLog();
                $amountData  = [
                    'uid' => $rechargeOrderInfo['uid'],
                    'amount' => $rechargeOrderInfo['amount'],
                    'amount_type' => 1,
                    'operation_source' => 1,
                    'amount_direction' => 1,
                    'create_time' => time(),
                    'correlation_id' => $rechargeOrderInfo['id'],
                    'gifts_amount' => $rechargeOrderInfo['give_amount'],
                ];
                $amountModel->insert($amountData);

                $userCommission  = new UserCommission();

                $userCommission->rechargeCommission($rechargeOrderInfo['uid'],$rechargeOrderInfo['id'], $rechargeOrderInfo['amount']);

                $rechargeOrderModel->commit();
                $currency_name = Config::getConfigValue('currency_name');
                $gzhMessage[0]['data'] = [
                    'amount13' => ['value' => $rechargeOrderInfo['price'].'元'],
                    'thing16' => ['value' => '充值余额'],
                    'amount8' => ['value' =>$totalNumber.$currency_name],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ];
                $gzhMessage[0]['uid'] =$rechargeOrderInfo['uid'];
                $gzhMessage[0]['title'] ='recharge';
                $messageModel = new MessageTemplate();
                $messageModel->sendMessage(1,$gzhMessage);
                $messageModel-> sendAliMessage($rechargeOrderInfo['uid'], 'recharge', ['money' =>$rechargeOrderInfo['price'],'desc'=> bcadd($rechargeOrderInfo['amount'],$rechargeOrderInfo['give_amount'],2)]);
            } catch (Exception $exception) {
                file_put_contents('./' . date('Y-m-d') . 'rechargeerror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
    public function rechargeXcxOrder(){
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'rechargedata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $pay_type = Config::getConfigValue('pay_type');
        if ($pay_type == 1) {
            $apiKey = Config::getConfigValue('xcx_apikey_v3');
        } else {
            $apiKey = Config::getConfigValue('xcx_m_apikey_v3');
        }
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $apiKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $rechargeOrderModel = new RechargeOrder();
            $rechargeOrderInfo =  $rechargeOrderModel->where(['order_sn' =>$out_trade_no] )->find();
            if ($rechargeOrderInfo['status'] != 1){
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }
            if ($pay_money != $rechargeOrderInfo['price']) {
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 3]);
            $userModel = new \app\common\model\User();
            try {
                $rechargeOrderModel->startTrans();
                $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 2,'pay_time' => time()]);
                $totalNumber = bcadd($rechargeOrderInfo['amount'],$rechargeOrderInfo['give_amount'],2);
                $userModel->where(['id' => $rechargeOrderInfo['uid']])->inc('balance',$totalNumber)->update();
                $amountModel = new AmountLog();
                $amountData  = [
                    'uid' => $rechargeOrderInfo['uid'],
                    'amount' => $rechargeOrderInfo['amount'],
                    'amount_type' => 1,
                    'operation_source' => 1,
                    'amount_direction' => 1,
                    'create_time' => time(),
                    'correlation_id' => $rechargeOrderInfo['id'],
                    'gifts_amount' => $rechargeOrderInfo['give_amount'],
                ];
                $amountModel->insert($amountData);
                $rechargeOrderModel->commit();
                $userCommission  = new UserCommission();
                $userCommission->rechargeCommission($rechargeOrderInfo['uid'],$rechargeOrderInfo['id'], $rechargeOrderInfo['amount']);
                $currency_name = Config::getConfigValue('currency_name');
                $xcxMessage[0]['data'] = [
                    'amount1' => ['value' => $rechargeOrderInfo['price']],
                    'thing8' => ['value' => $rechargeOrderInfo['amount'].$currency_name],
                    'amount11' => ['value' =>$rechargeOrderInfo['give_amount'].$currency_name],
                    'time2' => ['value' => date('Y-m-d H:i')],
                ];
                $xcxMessage[0]['uid'] =$rechargeOrderInfo['uid'];
                $xcxMessage[0]['title'] ='recharge';
                $messageModel = new MessageTemplate();
                $messageModel->sendMessage(3,$xcxMessage);
                $messageModel-> sendAliMessage($rechargeOrderInfo['uid'], 'recharge', ['money' =>$rechargeOrderInfo['price'],'desc'=> bcadd($rechargeOrderInfo['amount'],$rechargeOrderInfo['give_amount'],2)]);

            } catch (Exception $exception) {
                $rechargeOrderModel->rollback();
                file_put_contents('./' . date('Y-m-d') . 'rechargeerror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $rechargeOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
}